import decimal
import json
import re

from django.core.paginator import Paginator
from django.http import JsonResponse
from decimal import *
from django.shortcuts import render

# Create your views here.
# from apps.Merchants.models import Merchant
#
# Merchant.objects.create(
#     merchant_name='蜜雪冰城',
#     boss_phone='18911131111',
#     boss_pwd='12345678'
# )
from django.views import View

from apps.Category.models import GoodsCategory
from apps.Merchants.models import Merchant
from apps.OrderInfos.models import OrderInfo, OrderGoods
from apps.products.models import Product
from apps.users.models import User


# type = GoodsCategory.objects.get(id=7)
# type.delete()

class MerchantLoginView(View):
    """商家登录"""

    def post(self, request):
        data = json.loads(request.body.decode())
        phone = data.get('phone')
        password = data.get('password')
        if not all([phone, password]):
            return JsonResponse({'code': 400, 'errmsg': '信息不全或账号不存在'})
        if not re.match('1[3-9]\d{9}', phone):
            return JsonResponse({'code': 400, 'errmsg': '手机号格式错误'})
        phone_count = Merchant.objects.filter(boss_phone=phone).count()
        pwd_count = Merchant.objects.filter(boss_pwd=password).count()
        if phone_count != 1 or pwd_count == 0:
            return JsonResponse({'code': 400, 'errmsg': '手机号或者密码为空'})
        else:
            merchant = Merchant.objects.get(boss_phone=phone, boss_pwd=password)
        response = JsonResponse({'code': 0, 'errmsg': '登陆成功'})
        response.set_cookie('merchant_id', merchant.merchant_id, max_age=60 * 60 * 24)
        return response


class GetNameView(View):
    """获取商家名"""

    def get(self, request, id):
        try:
            merchant = Merchant.objects.get(merchant_id=id)
        except Merchant.DoesNotExist:
            return JsonResponse({'code': 400, 'errmsg': '商家id不存在'})
        name = merchant.merchant_name
        return JsonResponse({'code': 0, 'ermsg': 'ok', 'name': name})


class GetGoodsView(View):
    """获取商家的商品"""

    def get(self, request):
        page = request.GET.get('page')
        page_size = request.GET.get('page_size')
        ordering = request.GET.get('ordering')
        id = request.GET.get('id')
        products = Product.objects.filter(merchant_id=id, is_delete=False).order_by(ordering)
        paginator = Paginator(products, per_page=page_size)
        page_products = paginator.page(page)
        product_list = []
        for product in page_products.object_list:
            product_list.append({
                'id': product.product_id,
                'name': product.product_name,
                'image_url': product.img_url,
                'price': product.price,
                'stock': product.num,
                'type': Product.objects.get(product_id=product.product_id).type.type,
                'descript': product.description
            })
        total_count = paginator.num_pages
        return JsonResponse({'code': 0, 'errmsg': 'ok', 'products': product_list, 'count': total_count})


class InsertView(View):
    """新增商品"""

    def post(self, request):
        data = json.loads(request.body.decode())
        name = data.get('name')
        image_url = data.get('image_url')
        price = data.get('price')
        num = data.get('stock')
        type = data.get('type')
        description = data.get('description')
        merchant_id = data.get('merchant_id')
        if not all([name, image_url, price, type, merchant_id]):
            return JsonResponse({'code': 400, 'errmsg': '参数不全'})
        count = GoodsCategory.objects.filter(type=type).count()
        if count == 0:
            new_type = GoodsCategory.objects.create(type=type)
            new_type.save()
        try:
            types = GoodsCategory.objects.get(type=type)
        except GoodsCategory.DoesNotExist:
            return JsonResponse({'code': 400, 'errmsg': '类型不存在'})
        if not num and not description:
            product = Product.objects.create(
                product_name=name,
                img_url=image_url,
                price=decimal.Decimal(price).quantize(Decimal('0.00')),
                merchant_id=merchant_id,
                type_id=types.id,
            )
            product.save()
        elif not num and description:
            product = Product.objects.create(
                product_name=name,
                img_url=image_url,
                price=decimal.Decimal(price).quantize(Decimal('0.00')),
                # num=num,
                merchant_id=merchant_id,
                type_id=types.id,
                description=description
            )
            product.save()
        elif num and not description:
            product = Product.objects.create(
                product_name=name,
                img_url=image_url,
                price=decimal.Decimal(price).quantize(Decimal('0.00')),
                num=num,
                merchant_id=merchant_id,
                type_id=types.id,
                # description=description
            )
            product.save()
        else:
            product = Product.objects.create(
                product_name=name,
                img_url=image_url,
                price=decimal.Decimal(price).quantize(Decimal('0.00')),
                num=num,
                merchant_id=merchant_id,
                type_id=types.id,
                description=description
            )
            product.save()
        return JsonResponse({'code': 0, 'errmsg': '新增商品成功'})


# product = Product.objects.get(product_id=28)
# product.delete()
class ChangeView(View):
    """修改商品信息"""
    def put(self, request):
        data = json.loads(request.body.decode())
        product_id = data.get('id')
        new_descript = data.get('new_descript')
        new_price = data.get('new_price')
        print(new_descript)
        print(new_price)
        product = Product.objects.get(product_id=product_id)
        if not new_descript and not new_price:
            return JsonResponse({'code': 400, 'errmsg': '参数不全'})
        elif new_price and not new_descript:
            product.price = new_price
        elif not new_price and new_descript:
            product.description = new_descript
        product.save()
        return JsonResponse({'code': 0, 'errmsg': '修改成功'})
